/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package encrypt;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author ARMGARCES
 */
public class Encrypt {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            byte[] a = encrypt("Armando");
            System.out.println("a = " + a);
            String b = decrypt(a);
            System.out.println("b = " + b);
        } catch (GeneralSecurityException | UnsupportedEncodingException ex) {
            Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    /**
     * 
     * @param value
     * @return
     * @throws GeneralSecurityException
     * @throws UnsupportedEncodingException 
     */    
    public static byte[] encrypt(String value) throws GeneralSecurityException, UnsupportedEncodingException {

      byte[] raw = "Key for Encrypt!".getBytes();      
      if (raw.length != 16) {
        throw new IllegalArgumentException("Invalid key size!");
      }

      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
      return cipher.doFinal(value.getBytes());
    }
    
    /**
     * 
     * @param value
     * @return
     * @throws GeneralSecurityException 
     */
    public static String decrypt(byte[] value) throws GeneralSecurityException {

        byte[] raw = "Key for Encrypt!".getBytes();
        if (raw.length != 16) {
          throw new IllegalArgumentException("Invalid key size!");
        }
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(new byte[16]));        

        return new String(cipher.doFinal(value));
    }
}
